<template>
  <div class="data-management-container">
    <div class="header">
      <h2>设备数据管理</h2>
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>

    <!-- 设备选择 -->
    <div class="device-selector">
      <el-select v-model="selectedDevice" placeholder="选择设备" @change="handleDeviceChange">
        <el-option label="堆垛机" value="stacker" />
        <el-option label="设备1" value="device1" />
        <el-option label="设备2" value="device2" />
      </el-select>
    </div>

    <!-- 堆垛机数据表格 -->
    <div class="table-container" v-if="selectedDevice === 'stacker'">
      <div class="table-actions">
        <el-button type="success" @click="addRow">添加行</el-button>
        <el-button type="warning" @click="submitData" :loading="submitting"
        >提交到ThingsBoard</el-button
        >
      </div>

      <el-table :data="stackerData" border style="width: 100%" class="data-table">
        <el-table-column prop="deviceId" label="设备编号" width="120" fixed="left">
          <template #default="scope">
            <el-input v-model="scope.row.deviceId" size="small" placeholder="STK001" />
          </template>
        </el-table-column>

        <!-- X轴（水平）数据 -->
        <el-table-column label="X轴（水平）" align="center">
          <el-table-column prop="axisX_ActPosition" label="位置(mm)" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_ActPosition"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisX_ActSpeed" label="转速(RPM)" width="130">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_ActSpeed"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisX_setVelocity" label="速度(0.1m/min)" width="140">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_setVelocity"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisX_motorCurrent" label="电流" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_motorCurrent"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisX_motorTem" label="温度" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_motorTem"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisX_faultCode" label="故障码" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisX_faultCode"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
        </el-table-column>

        <!-- Y轴（提升）数据 -->
        <el-table-column label="Y轴（提升）" align="center">
          <el-table-column prop="axisY_ActPosition" label="位置(mm)" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_ActPosition"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisY_ActSpeed" label="转速(RPM)" width="130">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_ActSpeed"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisY_setVelocity" label="速度(0.1m/min)" width="140">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_setVelocity"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisY_motorCurrent" label="电流" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_motorCurrent"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisY_motorTem" label="温度" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_motorTem"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="axisY_faultCode" label="故障码" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.axisY_faultCode"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
        </el-table-column>

        <!-- Z1轴（货叉1）数据 -->
        <el-table-column label="Z1轴（货叉1）" align="center">
          <el-table-column prop="z1_ActPosition" label="位置(mm)" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_ActPosition"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="z1_ActSpeed" label="转速(RPM)" width="130">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_ActSpeed"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="z1_setVelocity" label="速度(0.1m/min)" width="140">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_setVelocity"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="z1_motorCurrent" label="电流" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_motorCurrent"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="z1_motorTem" label="温度" width="110">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_motorTem"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="z1_faultCode" label="故障码" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.z1_faultCode"
                size="small"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 任务状态 -->
        <el-table-column label="任务状态" align="center">
          <el-table-column prop="taskRow" label="任务行" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.taskRow"
                size="small"
                :min="1"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="taskCol" label="任务列" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.taskCol"
                size="small"
                :min="1"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="taskLayer" label="任务层" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.taskLayer"
                size="small"
                :min="1"
                :controls="true"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="runStatus" label="运行状态" width="140">
            <template #default="scope">
              <el-select v-model="scope.row.runStatus" size="small">
                <el-option label="停止" :value="0" />
                <el-option label="运行" :value="1" />
                <el-option label="故障" :value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="walkStatus" label="行走状态" width="140">
            <template #default="scope">
              <el-switch v-model="scope.row.walkStatus" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="liftStatus" label="升降状态" width="140">
            <template #default="scope">
              <el-switch v-model="scope.row.liftStatus" size="small" />
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 其他设备的简单表格 -->
    <div class="table-container" v-else-if="selectedDevice">
      <div class="table-actions">
        <el-button type="success" @click="addRow">添加行</el-button>
        <el-button type="warning" @click="submitData" :loading="submitting"
        >提交到ThingsBoard</el-button
        >
      </div>

      <el-table :data="otherDeviceData" border style="width: 100%" class="data-table">
        <el-table-column prop="deviceId" label="设备编号" width="15vw">
          <template #default="scope">
            <el-input v-model="scope.row.deviceId" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="value1" label="数值1" width="20vw">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.value1"
              size="small"
              :controls="true"
              controls-position="right"
            />
          </template>
        </el-table-column>
        <el-table-column prop="value2" label="数值2" width="20vw">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.value2"
              size="small"
              :controls="true"
              controls-position="right"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="15vw">
          <template #default="scope">
            <el-switch v-model="scope.row.status" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 提示信息 -->
    <div v-else class="no-device">
      <el-empty description="请选择设备类型" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { createDevice, getDefaultDeviceConfig } from '/@/api/thingsborad/entity/entity';
import { defHttp } from '/@/utils/http/axios';
import axios from 'axios';

const router = useRouter();
const selectedDevice = ref('');
const submitting = ref(false);
// const websocketStore = useWebsocketStoreWithOut();

// 堆垛机数据 - 基于真实数据结构
const stackerData = reactive([
  {
    deviceId: 'STK001',
    // X轴（水平）数据
    axisX_ActPosition: 0, // 当前位置mm
    axisX_ActSpeed: 0, // 当前电机转速RPM
    axisX_setVelocity: 0, // 设定速度0.1m/min
    axisX_motorCurrent: 0, // 电机电流
    axisX_motorTem: 25, // 电机温度
    axisX_faultCode: 0, // 故障代码

    // Y轴（提升）数据
    axisY_ActPosition: 0, // 当前位置mm
    axisY_ActSpeed: 0, // 当前电机转速RPM
    axisY_setVelocity: 0, // 设定速度0.1m/min
    axisY_motorCurrent: 0, // 电机电流
    axisY_motorTem: 25, // 电机温度
    axisY_faultCode: 0, // 故障代码

    // Z1轴（货叉1）数据
    z1_ActPosition: 0, // 当前位置mm
    z1_ActSpeed: 0, // 当前电机转速RPM
    z1_setVelocity: 0, // 设定速度0.1m/min
    z1_motorCurrent: 0, // 电机电流
    z1_motorTem: 25, // 电机温度
    z1_faultCode: 0, // 故障代码

    // 任务状态
    taskRow: 1, // 任务行(排）
    taskCol: 1, // 任务列
    taskLayer: 1, // 任务层
    runStatus: 0, // 运行状态
    walkStatus: false, // 行走状态
    liftStatus: false, // 升降状态
  },
]);

// 其他设备数据
const otherDeviceData = reactive([
  {
    deviceId: 'DEV001',
    value1: 0,
    value2: 0,
    status: false,
  },
]);

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 设备切换
const handleDeviceChange = (value: string) => {
  console.log('选择设备:', value);
};

// 添加行
const addRow = () => {
  if (selectedDevice.value === 'stacker') {
    stackerData.push({
      deviceId: '',
      axisX_ActPosition: 0,
      axisX_ActSpeed: 0,
      axisX_setVelocity: 0,
      axisX_motorCurrent: 0,
      axisX_motorTem: 25,
      axisX_faultCode: 0,
      axisY_ActPosition: 0,
      axisY_ActSpeed: 0,
      axisY_setVelocity: 0,
      axisY_motorCurrent: 0,
      axisY_motorTem: 25,
      axisY_faultCode: 0,
      z1_ActPosition: 0,
      z1_ActSpeed: 0,
      z1_setVelocity: 0,
      z1_motorCurrent: 0,
      z1_motorTem: 25,
      z1_faultCode: 0,
      taskRow: 1,
      taskCol: 1,
      taskLayer: 1,
      runStatus: 0,
      walkStatus: false,
      liftStatus: false,
    });
  } else {
    otherDeviceData.push({
      deviceId: '',
      value1: 0,
      value2: 0,
      status: false,
    });
  }
};

// 删除行
const deleteRow = (index: number) => {
  if (selectedDevice.value === 'stacker') {
    stackerData.splice(index, 1);
  } else {
    otherDeviceData.splice(index, 1);
  }
};

// 提交数据到ThingsBoard
const submitData = async () => {
  if (!selectedDevice.value) {
    ElMessage.warning('请先选择设备类型');
    return;
  }

  submitting.value = true;

  try {
    const dataToSubmit = selectedDevice.value === 'stacker' ? stackerData : otherDeviceData;

    // 验证数据
    const validData = dataToSubmit.filter((item: any) => item.deviceId && item.deviceId.trim());
    if (validData.length === 0) {
      ElMessage.warning('请至少填写一行有效数据（设备编号不能为空）');
      return;
    }

    // 获取默认设备配置
    const defaultConfig = await getDefaultDeviceConfig();

    // 为每个设备创建设备并发送遥测数据
    for (const deviceData of validData) {
      await createDeviceAndSendTelemetry(deviceData, defaultConfig);
    }

    ElMessage.success(`成功提交 ${validData.length} 条${getDeviceTypeName()}数据到ThingsBoard！`);
  } catch (error) {
    console.error('提交数据失败:', error);
    ElMessage.error('数据提交失败：' + (error as Error).message);
  } finally {
    submitting.value = false;
  }
};

// 创建设备并发送遥测数据
const createDeviceAndSendTelemetry = async (deviceData: any, defaultConfig: any) => {
  try {
    let deviceUUID = null;

    // 1. 创建设备（如果不存在）
    const deviceParams = {
      name: deviceData.deviceId,
      type: getDeviceTypeName(),
      label: deviceData.deviceId,
      deviceProfileId: defaultConfig.id,
      additionalInfo: {
        description: `${getDeviceTypeName()} - ${deviceData.deviceId}`,
      },
    };

    try {
      const deviceResult = await createDevice(deviceParams);
      console.log(`设备 ${deviceData.deviceId} 创建成功:`, deviceResult);
      deviceUUID = deviceResult.id.id; // 获取设备UUID
    } catch (deviceError: any) {
      console.error('设备创建失败:', deviceError);
      throw deviceError;
    }

    // 2. 使用设备UUID发送遥测数据
    if (deviceUUID) {
      await sendTelemetryData({...deviceData, deviceUUID});
    } else {
      throw new Error('无法获取设备UUID');
    }
  } catch (error) {
    console.error(`设备 ${deviceData.deviceId} 处理失败:`, error);
    throw error;
  }
};

// 发送遥测数据 - 简洁高效版本
const sendTelemetryData = async (deviceData: any) => {
  try {
    // 构建遥测数据
    let telemetryPayload: any = {};

    if (selectedDevice.value === 'stacker') {
      // 堆垛机数据
      telemetryPayload = {
        axisX_ActPosition: deviceData.axisX_ActPosition || 0,
        axisX_ActSpeed: deviceData.axisX_ActSpeed || 0,
        axisX_setVelocity: deviceData.axisX_setVelocity || 0,
        axisX_motorCurrent: deviceData.axisX_motorCurrent || 0,
        axisX_motorTem: deviceData.axisX_motorTem || 25,
        axisX_faultCode: deviceData.axisX_faultCode || 0,
        axisY_ActPosition: deviceData.axisY_ActPosition || 0,
        axisY_ActSpeed: deviceData.axisY_ActSpeed || 0,
        axisY_setVelocity: deviceData.axisY_setVelocity || 0,
        axisY_motorCurrent: deviceData.axisY_motorCurrent || 0,
        axisY_motorTem: deviceData.axisY_motorTem || 25,
        axisY_faultCode: deviceData.axisY_faultCode || 0,
        z1_ActPosition: deviceData.z1_ActPosition || 0,
        z1_ActSpeed: deviceData.z1_ActSpeed || 0,
        z1_setVelocity: deviceData.z1_setVelocity || 0,
        z1_motorCurrent: deviceData.z1_motorCurrent || 0,
        z1_motorTem: deviceData.z1_motorTem || 25,
        z1_faultCode: deviceData.z1_faultCode || 0,
        taskRow: deviceData.taskRow || 1,
        taskCol: deviceData.taskCol || 1,
        taskLayer: deviceData.taskLayer || 1,
        runStatus: deviceData.runStatus || 0,
        walkStatus: deviceData.walkStatus || false,
        liftStatus: deviceData.liftStatus || false
      };
    } else {
      // 其他设备数据
      telemetryPayload = {
        value1: deviceData.value1 || 0,
        value2: deviceData.value2 || 0,
        status: deviceData.status || false
      };
    }

    // 使用axios直接发送，绕过defHttp的包装
    // 正确获取JWT token
    const getJwtToken = () => {
      const storageKey = 'THINGS_VUE__DEVELOPMENT__1.1.0__COMMON__LOCAL__KEY__';
      const storageData = localStorage.getItem(storageKey);
      if (storageData) {
        const parsed = JSON.parse(storageData);
        return parsed.value?.TOKEN__?.value;
      }
      return null;
    };

    const token = getJwtToken();
    const response = await axios.post(
      `http://192.168.10.14:8088/api/plugins/telemetry/DEVICE/${deviceData.deviceUUID}/timeseries/SERVER_SCOPE`, // 使用UUID而不是deviceId
      {
        ts: Date.now(),
        values: telemetryPayload
      },
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`✅ 设备 ${deviceData.deviceId} 遥测数据发送成功`);
    return response.data;
  } catch (error: any) {
    console.error(`❌ 设备 ${deviceData.deviceId} 遥测数据发送失败:`, error.response?.data || error.message);
    throw new Error(`遥测数据发送失败: ${error.response?.data?.message || error.message}`);
  }
};

// 获取设备类型中文名称
const getDeviceTypeName = () => {
  const names: Record<string, string> = {
    stacker: '堆垛机',
    device1: '设备1',
    device2: '设备2',
  };
  return names[selectedDevice.value] || selectedDevice.value;
};

// 根据设备名称获取设备UUID的简单方法
const getDeviceUUIDByName = async (deviceName: string) => {
  try {
    const token = getJwtToken();
    // 使用ThingsBoard的设备查询API
    const response = await axios.get(
      `http://192.168.10.14:8088/api/tenant/devices?deviceName=${deviceName}`,
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.data && response.data.length > 0) {
      return response.data[0].id.id; // 返回第一个匹配设备的UUID
    }
    throw new Error(`未找到设备: ${deviceName}`);
  } catch (error: any) {
    console.error(`获取设备UUID失败:`, error.response?.data || error.message);
    throw error;
  }
};
</script>

<style scoped>
.data-management-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  color: white;
}

.device-selector {
  margin-bottom: 20px;
}

.device-selector .el-select {
  width: 200px;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
  width: 100%;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.data-table {
  margin-bottom: 20px;
}

/* 确保数字输入框控制按钮显示 */
:deep(.el-input-number) {
  width: 100% !important;
  min-width: 100px !important;
}

:deep(.el-input-number .el-input-number__increase),
:deep(.el-input-number .el-input-number__decrease) {
  display: block !important;
  width: 24px !important;
  height: 14px !important;
  line-height: 14px !important;
  border: 1px solid #dcdfe6 !important;
  background: #f5f7fa !important;
  visibility: visible !important;
  opacity: 1 !important;
}

:deep(.el-input-number--small .el-input-number__increase),
:deep(.el-input-number--small .el-input-number__decrease) {
  width: 24px !important;
  height: 14px !important;
  line-height: 12px !important;
}

:deep(.el-input-number .el-input__inner) {
  padding-right: 30px !important;
}

.no-device {
  background: white;
  padding: 40px;
  border-radius: 8px;
  text-align: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: center;
}

:deep(.el-table .el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

/* 固定列样式 */
:deep(.el-table__fixed) {
  box-shadow: 2px 0 6px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 6px rgba(0, 0, 0, 0.1);
}
</style>
